package com.toolsDemo.importDemo.excelImportController;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.toolsDemo.importDemo.listener.DemoListener;
import com.toolsDemo.importDemo.po.DemoPO;
import com.toolsDemo.importDemo.util.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

@Controller
@RequestMapping(value = "/excelImport")
public class ExcelImportController {

    @RequestMapping(value = "/toImportPage")
    public String toImportPage(){
        return "excelImport";
    }

    @RequestMapping(value = "/imp")
    @ResponseBody
    public Result imp(HttpServletRequest request, @ModelAttribute("uploadfile") MultipartFile uploadfile){
        Result result = new Result();
        ExcelReader excelReader = null;
        try {
            excelReader = EasyExcel.read(uploadfile.getInputStream(), DemoPO.class,new DemoListener()).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            result.setResultCode("1");
        }catch (Exception e){
            result.setResultCode("1");
            result.setMessage(e.getMessage());
            System.out.println(e);
        }finally {
            //Cose ExcelReader
            if (excelReader != null){
                excelReader.finish();
            }
        }
        return result;
    }
}
